package com.sfac.interceptor;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Author:唐琳的爹
 * @BelongsProject:hqyj_springboot
 * @BelongsPackage:com.sfac.interceptor
 * @CreateTime:2022/8/22 13:38:34
 */
@Component
@Slf4j
public class ViewMappingInterceptor implements HandlerInterceptor {



    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.debug("============preHandle============");
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        log.debug("============postHandle============");
        // 判断请求是否为接口,如果是接口则直接返回
        if (modelAndView == null){
            // 如果为空则不是请求页面
            return;
        }

        // 判断页面请求是否为重定向或者转发，如果是则直接返回
        if (modelAndView.getViewName() != null){
            if (modelAndView.getViewName().startsWith("redirect")||
                modelAndView.getViewName().startsWith("forward")){return;}
        }

        // 获取请求路经
        String path = request.getServletPath();

        // 判断modelMap中是否有template，有则跳过，如果没有则设置template
        String template = (String) modelAndView.getModelMap().get("template");
        if (StringUtils.isBlank(template)){
            modelAndView.getModelMap().addAttribute("template",
                    path.substring(1,path.length()));
        }
        // 将处理之后的结果返回
        HandlerInterceptor.super.postHandle(request,response,handler,modelAndView);

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        log.debug("============afterHandle============");
    }
}
